package downAdmin

import (
	"archive/tar"
	"context"
	"fmt"
	"io"
	"mysqlAdmin/lib/log"
	"os"
	"os/exec"
	"path/filepath"

	"github.com/xi2/xz"

	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gfile"
)

func Down() {

	home := "/opt/mysql/"
	version := "mysql-8.0.29-linux-glibc2.12-x86_64.tar"
	localPath := filepath.Join(home, version)
	os.Remove(localPath)

	log.Infof("下载:%s", version)

	url := fmt.Sprintf("https://cdn.mysql.com/Downloads/MySQL-8.0/%s", version)

	ctx := context.TODO()
	r, err := g.Client().Get(ctx, url)

	if err != nil {
		log.Error("异常，无法下载文件")
		panic(err)
	}
	defer r.Close()

	mkMySQLHOME()

	gfile.PutBytes(localPath, r.ReadAll())
	log.Infof("下载完成:%s", localPath)

}

func mkMySQLHOME() {
	home := "/opt/mysql"
	if _, err := os.Stat(home); os.IsNotExist(err) {
		os.MkdirAll(home, 0750)
	}

	err := os.Chown(home, 27, 27)
	if err != nil {
		log.Errorf("文件夹路径权限修改失败,%v", err)
	}

}

func Install() {
	file := "mysql-8.0.29-linux-glibc2.12-x86_64.tar"
	version := "mysql-8.0.29-linux-glibc2.12-x86_64"
	unTar(file, version)
}

func unTar(fileName, version string) {
	cmd := exec.Command("tar", "xvf", fileName, "-C", "/tmp")
	_ = cmd.Run()

	tmpFile := fmt.Sprintf("/tmp/%s.tar.xz", version)
	cmd = exec.Command("tar", "xvf", tmpFile, "-C", "/opt/mysql")
	_ = cmd.Run()

	tmpDir := fmt.Sprintf("/opt/mysql/%s", version)
	cmd = exec.Command("mv", tmpDir, "/usr/local/mysql")
	_ = cmd.Run()

	cmd = exec.Command("chown", "-R", "mysql.mysql", "/usr/local/mysql")
	_ = cmd.Run()

}

func exeCommand(command string) {

}

func unTarFile(fileName, dirName string) {
	f, err := os.Open(fileName)
	if err != nil {
		log.Fatalf("异常", err)
	}
	// Create an xz Reader
	r, err := xz.NewReader(f, 0)
	if err != nil {
		log.Fatalf("异常", err)
	}
	// Create a tar Reader
	tr := tar.NewReader(r)
	// Iterate through the files in the archive.
	for {
		hdr, err := tr.Next()
		if err == io.EOF {
			// end of tar archive
			break
		}
		if err != nil {
			log.Fatalf("异常", err)
		}
		switch hdr.Typeflag {
		case tar.TypeDir:
			// create a directory
			fmt.Println("creating:   " + hdr.Name)
			err = os.MkdirAll(hdr.Name, 0777)
			if err != nil {
				log.Fatalf("异常", err)
			}
		case tar.TypeReg, tar.TypeRegA:
			// write a file
			fmt.Println("extracting: " + hdr.Name)
			w, err := os.Create(hdr.Name)
			if err != nil {
				log.Fatalf("异常", err)
			}
			_, err = io.Copy(w, tr)
			if err != nil {
				log.Fatalf("异常", err)
			}
			w.Close()
		}
	}
	f.Close()
}
